﻿using MvvmCross.Platform;
using MvvmCross.Plugins.Messenger;
using Sidvall.WorkItemManager.UI.Messaging;
using XXX.Workflow;

namespace XXX.UI.ViewModels
{
	public class WorkItem1ExecutionContextViewModel : Sidvall.UI.ViewModels.ViewModelBase
	{
		#region Public Members

		#region Context

		private string _Context;
		public string Context
		{
			get
			{
				return _Context;
			}
			set
			{
				if (_Context == value)
					return;
				_Context = value;
				RaisePropertyChanged("Context");
			}
		}

		#endregion
		#region ContextItem

		private WorkItem1ExecutionContext _ContextItem;
		public WorkItem1ExecutionContext ContextItem
		{
			get
			{
				return _ContextItem;
			}
			set
			{
				if (_ContextItem != null)
					_ContextItem.PropertyChanged -= OnWorkItemContextPropertyChanged;
				_ContextItem = value;
				if (_ContextItem != null)
					_ContextItem.PropertyChanged += OnWorkItemContextPropertyChanged;
				RaisePropertyChanged("ContextItem");
				OnContextItemChanged();
			}
		}

		#endregion

		#region OnContextItemChanged

		protected void OnContextItemChanged()
		{
			this.Context = Sidvall.Serialization.SerializerManager.Current.SerializeObject(this.ContextItem);
		}

		#endregion
		#region OnWorkItemContextPropertyChanged

		private void OnWorkItemContextPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			this.Context = Sidvall.Serialization.SerializerManager.Current.SerializeObject(this.ContextItem);
		}

		#endregion

		#region Init

		public void Init(ContextParameter item)
		{
			this.ContextParameter = item;
		}

		#endregion
		#region InitializeContext

		public virtual void InitializeContext()
		{
			this.ContextItem = Sidvall.Serialization.SerializerManager.Current.Deserialize<WorkItem1ExecutionContext>(this.Context);
		}

		#endregion
		#region Start

		public override void Start()
		{
			var messenger = Mvx.Resolve<IMvxMessenger>();
			_WorkItemExecutionContextMessageToken = messenger.Subscribe<WorkItemExecutionContextMessage>(OnWorkItemExecutionContextMessage);

			if (this.ContextParameter != null)
			{
				this.Context = this.ContextParameter.Context;
				InitializeContext();
				this.ContextParameter = null;
			}
		}

		#endregion

		#endregion
		#region Private Members

		private ContextParameter ContextParameter { get; set; }

		#region OnWorkItemExecutionContextMessage

		private MvxSubscriptionToken _WorkItemExecutionContextMessageToken;
		private void OnWorkItemExecutionContextMessage(WorkItemExecutionContextMessage item)
		{
			if (this.Context == item.Context)
				return;
			this.Context = item.Context;
			InitializeContext();
		}

		#endregion

		#endregion
	}
}
